<?php
/**
 * 支付数据更新服务
 */

namespace polymerize\order\service;

use app\common\VipStatus;
use app\model\User;
use app\model\VipOrder;
use app\service\AppleService;
use app\service\OrderService;
use support\Redis;
use think\facade\Db;

class PayModelService
{

    public static ?PayModelService $_instance = null;

    /**
     * @return PayModelService|mixed
     */
    public static function instance(): ?PayModelService
    {
        if (!static::$_instance) static::$_instance = new self();
        return static::$_instance;
    }

    /**
     * 充值支付成功后更新
     *
     * @param string $orderNo
     * @param int    $uid
     * @param string $payTime
     * @param string $tradeNo
     * @return array
     */
    public function updateModelByCZPaySuccess(string $orderNo, int $uid, string $payTime, string $tradeNo): array
    {
        if (empty($orderNo)) return ['code' => 400, 'msg' => '订单号错误'];

        $userwhere[]   = ['id', '=', $uid];
        $userInfo      = User::getOne($userwhere);
        $walletBalance = (int)$userInfo['wallet_balance'];
        $sumConsume    = (int)$userInfo['sum_consume'];

        // 启动事务
        Db::startTrans();
        try {
            $dateTime = date('Y-m-d H:i:s');
            //用户账单
            $data = [
                'status'   => 1,//支付成功
                'pay_time' => $payTime,
                'u_time'   => $dateTime,
                'trade_no' => $tradeNo,
            ];
            Db::table('user_bill')->where('order_no', $orderNo)->update($data);

            //用户余额和累计消费
            $data = [
                'u_time'         => $dateTime,
                'sum_consume'    => $sumConsume + $walletBalance,
            ];
            Db::table('user')->where('id', $uid)->update($data);

            // 提交事务
            Db::commit();
            return ['code' => 200, 'msg' => '操作成功'];
        } catch (\Throwable $e) {
            // 回滚事务
            Db::rollback();
            $errorMessage = $e->getMessage();
            return ['code' => 400, 'msg' => $errorMessage];
        }
    }

    /**
     * 订单退款成功后数据更新
     *
     * @param string $tradeNo
     * @param string $originalTransactionId
     * @param string $content
     * @param int    $payType
     * @return array
     */
    public function updateModelByRefund(string $tradeNo, string $originalTransactionId, string $content, int $payType): array
    {
        $vipOrderModel = new VipOrder();
        if (empty($orderNo)) return ['code' => 400, 'msg' => '订单号错误'];
        $orderInfo = $vipOrderModel
            ->where('trade_no', $tradeNo)
            ->where('original_transaction_id', $originalTransactionId)
            ->findOrEmpty();
        if (empty($orderInfo)) return ['code' => 400, 'msg' => '获取订单信息失败'];
        if ($orderInfo['status'] != 1) return ['code' => 400, 'msg' => '当前订单不支持退款'];

        $dateTime = date('Y-m-d H:i:s');

        // 启动事务
        Db::startTrans();
        try {
            // 修改订单状态为退款
            $upData1 = [
                'status' => 4,
                'u_time' => $dateTime
            ];
            Db::table('vip_order')->where('id', $orderInfo['id'])->update($upData1);

            // 提交事务
            Db::commit();
            return ['code' => 200, 'msg' => '退款成功'];
        } catch (\Throwable $e) {
            // 回滚事务
            Db::rollback();
            $errorMessage = $e->getMessage();
            return ['code' => 400, 'msg' => $errorMessage];
        }
    }

    /**
     * 苹果恢复购买
     *
     * @param string $originalTransactionId
     * @param int    $newUid
     * @return array
     */
    public function resumePurchaseByApple(string $originalTransactionId, int $newUid): array
    {
        if (!$originalTransactionId || !$newUid) return ['code' => 400, 'msg' => '参数错误'];

//        //查询用户对该原始订单是否已经恢复了
//        $wherelog[]                      = ['original_transaction_id', '=', $originalTransactionId];
//        $wherelog[]                      = ['uid', '=', $newUid];
//        $userApppleResumePurchaseLogInfo = UserApppleResumePurchaseLog::getOne($wherelog);
//        if ($userApppleResumePurchaseLogInfo) return ['code' => 200, 'msg' => '已恢复'];

        $where1[]  = ['original_transaction_id', '=', $originalTransactionId];
        $where1[]  = ['pay_type', '=', 3];
        $where1[]  = ['status', '=', 1];
        $orderInfo = VipOrder::getOne($where1);
        if (!$orderInfo) return ['code' => 200, 'msg' => '订单不存在'];
        $oldUid   = $orderInfo['uid'];
        $dateTime = date('Y-m-d H:i:s');

        //1小时内只能恢复购买一次
        $jiaSuoRedisKey1 = "app:resumePurchaseByApples:newUid:$newUid:oldUid:$oldUid";
        $jiaSuoRedisRes1 = Redis::get($jiaSuoRedisKey1);
        $jiaSuoRedisKey2 = "app:resumePurchaseByApples:newUid:$newUid:newUid:$newUid";
        $jiaSuoRedisRes2 = Redis::get($jiaSuoRedisKey2);
        if ($jiaSuoRedisRes1 || $jiaSuoRedisRes2) return ['code' => 200, 'msg' => '已恢复'];

        // 启动事务
        Db::startTrans();
        try {
            //加锁
            Redis::set($jiaSuoRedisKey1, 1, 'EX', 60 * 1, 1);
            Redis::set($jiaSuoRedisKey2, 1, 'EX', 60 * 1, 1);

            $content = '苹果恢复购买,原用户id=' . $oldUid . '的所有订单变成为新用户id=' . $newUid;
            // 记录退款信息
            $data = [
                'order_id'              => $orderInfo['id'],
                'transaction_id'        => $originalTransactionId,
                'out_refund_no'         => $originalTransactionId,
                'refund_id'             => $originalTransactionId,
                'user_received_account' => '',
                'refund_status'         => 'Success',
                'content'               => $content,
                'pay_type'              => 34,//恢复购买
                'status'                => 1,
                'date_v'                => $dateTime,
            ];
            Db::table('vip_order_refund_log')->insert($data);

            // 提交事务
            Db::commit();
            return ['code' => 200, 'msg' => '操作成功'];
        } catch (\Throwable $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => 400, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 苹果订单支付结果查询
     *
     * @param int    $uid
     * @param string $orderNo               本系统订单号
     * @param string $receiptData           票据base64
     * @param int    $sandbox               1沙盒
     * @param string $productId             产品id
     * @param int    $transactionId         苹果本次订单号
     * @param int    $originalTransactionId 原始订单号
     * @param int    $disposableGoods
     * @return array
     */
    public function payOrderQueryBastByApple(int $uid, string $orderNo, string $receiptData, int $sandbox, string $productId, int $transactionId, int $originalTransactionId, int $disposableGoods): array
    {
        //订阅有效期内第二次购买不扣款，告诉用户已支付了
        $where1[]  = ['uid', '=', $uid];
        $where1[]  = ['trade_no', '=', $transactionId];
        $where1[]  = ['original_transaction_id', '=', $originalTransactionId];
        $where1[]  = ['pay_type', 'in', [3, 33]];
        $where1[]  = ['status', '=', 1];
        $orderInfo = VipOrder::getOne($where1);
        if ($orderInfo) return ['code' => 400, 'msg' => '已支付了'];

        $where2[]  = ['order_no', '=', $orderNo];
        $where2[]  = ['uid', '=', $uid];
        $where2[]  = ['pay_type', '=', 3];
        $orderInfo = VipOrder::getOne($where2);
        if (!$orderInfo) return ['code' => 400, 'msg' => '订单不存在'];
        if ($orderInfo['status'] == 1) return ['code' => 400, 'msg' => '已支付'];

        $res = ['code' => 400, 'msg' => '支付失败'];

        $query = AppleService::instance()->validateApplePay($receiptData, $sandbox);
        if ($query['code'] != 200) return ['code' => 400, 'msg' => $query['msg']];
        $query = $query['data'];

        //订阅商品
        if (is_array($query) && ($disposableGoods == 0) && isset($query['receipt']['in_app'])) {
            $count        = count($query['receipt']['in_app']);
            $newOrderInfo = $query['receipt']['in_app'][$count - 1];
            if (isset($newOrderInfo['product_id'])) {
                if (($newOrderInfo['product_id'] == $productId) && ($newOrderInfo['transaction_id'] == $transactionId) && ($newOrderInfo['original_transaction_id'] == $originalTransactionId)) {
                    $payTime          = $newOrderInfo['purchase_date'];
                    $payTime          = getBeforeString($payTime, ' Etc/GMT');
                    $payTimeByBeiJing = date('Y-m-d H:i:s', strtotime($payTime) + 8 * 3600);
                }
            }
        }

        //一次性商品
        if (is_array($query) && ($disposableGoods == 1) && isset($query['receipt']['in_app'])) {
            $newOrderInfo = [];
            foreach ($query['receipt']['in_app'] as $value) {
                if ($value['product_id'] == $productId) {
                    $newOrderInfo = $value;
                    break;
                }
            }

            if (isset($newOrderInfo['product_id'])) {
                if (($newOrderInfo['product_id'] == $productId) && ($newOrderInfo['transaction_id'] == $transactionId) && ($newOrderInfo['original_transaction_id'] == $originalTransactionId)) {
                    $payTime          = $newOrderInfo['purchase_date'];
                    $payTime          = getBeforeString($payTime, ' Etc/GMT');
                    $payTimeByBeiJing = date('Y-m-d H:i:s', strtotime($payTime) + 8 * 3600);
                }
            }
        }

        if ($res['code'] != 400) {
            //记录票据日志
            $data = [
                'uid'                     => $uid,
                'order_no'                => $orderNo,
                'receipt_data'            => $receiptData,
                'product_id'              => $productId,
                'transaction_id'          => $transactionId,
                'original_transaction_id' => $originalTransactionId,
                'sandbox'                 => $sandbox,
                'disposable_goods'        => $disposableGoods,
            ];
            (new VipOrderApplePlayLog)->insert($data);
        }

        return $res;
    }

    /**
     * 苹果支付续订成功后创建订单和用户会员表
     *
     * @param string $payTime
     * @param string $tradeNo
     * @param string $originalTransactionId
     * @return array
     */
    public function addModelByApplePayDidRenew(string $payTime, string $tradeNo, string $originalTransactionId): array
    {
        $vipOrderModel = new VipOrder();
        if (!$originalTransactionId) return ['code' => 400, 'msg' => '原始订单号错误'];
        $orderInfo = $vipOrderModel->where('status', 1)->where('pay_type', 3)->where('original_transaction_id', $originalTransactionId)->findOrEmpty();
        if (!$orderInfo) return ['code' => 400, 'msg' => '获取订单信息失败'];

        $dateTime     = date('Y-m-d H:i:s');
        $uid          = $orderInfo['uid'];
        $vipConfigId   = $orderInfo['vip_config_id'];

        // 启动事务
        Db::startTrans();
        try {
            $orderNo = OrderService::instance()->getOrderNo($uid);
            $data    = [
                'uid'                     => $uid,
                'order_no'                => $orderNo,
                'trade_no'                => $tradeNo,
                'original_transaction_id' => $originalTransactionId,
                'status'                  => 1,
                'pay_time'                => $payTime,
                'date_v'                  => date('Y-m-d'),
                'pay_type'                => 33,//苹果续订
                'payment'                 => '"apple"',
                'u_time'                  => $dateTime,
                'vip_config_id'           => $vipConfigId,
                'os_type'                 => $orderInfo['os_type'],
            ];
            Db::table('vip_order')->insert($data);

            // 提交事务
            Db::commit();
            return ['code' => 200, 'msg' => '操作成功'];
        } catch (\Throwable $e) {
            // 回滚事务
            Db::rollback();
            $errorMessage = $e->getMessage();
            return ['code' => 400, 'msg' => $errorMessage];
        }
    }


}
    